package person.zjh.kaoyansharehub.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import person.zjh.kaoyansharehub.dto.PageReplyDTO;
import person.zjh.kaoyansharehub.dto.ReplyCreateDTO;
import person.zjh.kaoyansharehub.mapper.ReplyMapper;
import person.zjh.kaoyansharehub.mapper.UserMapper;
import person.zjh.kaoyansharehub.pojo.Reply;
import person.zjh.kaoyansharehub.pojo.User;
import person.zjh.kaoyansharehub.result.PageResult;
import person.zjh.kaoyansharehub.result.Result;
import person.zjh.kaoyansharehub.service.ReplyService;
import person.zjh.kaoyansharehub.vo.ReplyVO;

import java.util.List;

/**
 * @description: TODO
 * @author 郑佳豪
 * @date 2025/2/22 16:22
 * @version 1.0
 */
@Service
@RequiredArgsConstructor
public class ReplyServiceImpl extends ServiceImpl<ReplyMapper, Reply> implements ReplyService {


    private final ReplyMapper replyMapper;
    private final UserMapper userMapper;


    @Override
    public Result saveReply(ReplyCreateDTO requestParam) {
        Reply reply = Reply.builder()
                .userId(requestParam.getUserId())
                .content(requestParam.getContent())
                .commentId(requestParam.getCommentId())
                .build();
        replyMapper.insert(reply);

        return Result.success();

    }

    @Override
    public PageResult getReplyList(PageReplyDTO requestParam) {
        PageHelper.startPage(requestParam.getPageNum(),requestParam.getPageSize());
        LambdaQueryWrapper<Reply> wrapper = new LambdaQueryWrapper<Reply>()
                .eq(Reply::getCommentId, requestParam.getCommentId())
                .orderByDesc(Reply::getCreatedAt);

        List<Reply> replyList = replyMapper.selectList(wrapper);
        PageInfo pageInfo = new PageInfo(replyList);
        List<ReplyVO> replyVOS = BeanUtil.copyToList(replyList, ReplyVO.class);
        for (ReplyVO replyVO : replyVOS) {
            User user = userMapper.selectById(replyVO.getUserId());
            replyVO.setUserAvatarPath(user.getAvatar());
            replyVO.setUserName(user.getUserName());
        }

        return new PageResult(pageInfo.getTotal(),replyVOS);
    }
}
